import { Inject, Injectable, forwardRef } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Dept } from "./entities/dept.entity";
import { FindConditions, Like, Repository } from "typeorm";
import { ReqAddDeptDto, ReqDeptListDto } from "./dto/req-dept.dto";
import { SharedService } from "src/shared/shared.service";
import { ApiException } from "src/common/exceptions/api.exception";
import { UserService } from "../user/user.service";
import { RoleService } from "../role/role.service";

@Injectable()
export class DeptService {
  constructor(
    @InjectRepository(Dept) private readonly deptRepository: Repository<Dept>,
    @Inject(forwardRef(() => UserService)) private readonly userService: UserService,
    private readonly roleService: RoleService,
    private readonly sharedService: SharedService,
  ) {}

  // 新增/编辑部门
  async addOrUpdate(reqAddDeptDto: ReqAddDeptDto) {
    if (reqAddDeptDto.parentId) {
      // 父级部门
      const parentDept = await this.getDeptById(reqAddDeptDto.parentId);
      reqAddDeptDto.parent = parentDept;
    }
    await this.deptRepository.save(reqAddDeptDto);
  }

  // 查询部门列表
  async getDeptList(reqDeptListDto: ReqDeptListDto) {
    let where: FindConditions<Dept> = { del_flag: "0" };
    if (reqDeptListDto.dept_name) {
      where.dept_name = Like(`%${reqDeptListDto.dept_name}%`);
    }
    if (reqDeptListDto.status) {
      where.status = reqDeptListDto.status;
    }

    const deptList = await this.deptRepository
      .createQueryBuilder("dept")
      .select("dept.dept_id", "dept_id")
      .addSelect("dept.dept_name", "dept_name")
      .addSelect("dept.leader", "leader")
      .addSelect("dept.order_num", "order_num")
      .addSelect("dept.status", "status")
      .addSelect("dept.create_time", "create_time")
      .addSelect("ifnull(dept.parentDeptId,0)", "parentId")
      .where(where)
      .orderBy("dept.order_num", "ASC")
      .addOrderBy("dept.create_time", "ASC")
      .getRawMany();

    const deptTreeList = [];
    this.sharedService.handleTree(deptList, "dept_id").forEach((item) => {
      item.dept_id = String(item.dept_id);
      deptTreeList.push(item);
    });
    return deptTreeList;
  }

  // 通过id查询
  async getDeptById(dept_id: string | number) {
    return this.deptRepository.findOne(dept_id);
  }

  // 删除部门
  async deleteDeptById(dept_id: string | number) {
    // 1.通过部门id获取用户，如果存在用户，不允许删除
    const users = await this.userService.getUserInfoByDeptId(dept_id);

    if (users.length > 0) {
      // 部门下有用户，不允许删除
      throw new ApiException("该角色下存在用户，不允许删除！");
    }
    return this.deptRepository.delete(dept_id);
  }
}
